/**
 *新闻动态管理js
 */

var pageCurr;
var form;
var E;
var editor;
$(function () {

    //初始化富文本编辑器
    E = window.wangEditor;
    editor = new E('#editor');

    //开启debug模式
    editor.customConfig.debug = true;
    // 关闭粘贴内容中的样式
    editor.customConfig.pasteFilterStyle = false;

    editor.customConfig.pasteTextHandle = function (content) {

        // content 即粘贴过来的内容（html 或 纯文本），可进行自定义处理然后返回
        if (content == '' && !content) return ''
        var str = content
        str = str.replace(/<xml>[\s\S]*?<\/xml>/ig, '')
        str = str.replace(/<style>[\s\S]*?<\/style>/ig, '')
        str = str.replace(/<\/?[^>]*>/g, '')
        str = str.replace(/[ | ]*\n/g, '\n')
        str = str.replace(/&nbsp;/ig, '')
        console.log('****', content)
        console.log('****', str)
        return str
    }

    // 忽略粘贴内容中的图片
    editor.customConfig.pasteIgnoreImg = true;
    // 使用 base64 保存图片
    //editor.customConfig.uploadImgShowBase64 = true
    // http://localhost:8011/uploadfiles/5168898981064558.jpeg

    editor.customConfig.uploadTimeout = 100000000;

    editor.customConfig.uploadFileName = "file";
    editor.customConfig.uploadImgServer = '/file/fileUpload';
    editor.customConfig.debug = true;

    //自定义上传图片事件
    editor.customConfig.uploadImgHooks = {
        before: function (xhr, editor, files) {

        },
        success: function (xhr, editor, result) {
            console.log("上传成功");
        },
        fail: function (xhr, editor, result) {
            console.log("上传失败,原因是" + result);
        },
        error: function (xhr, editor) {
            console.log("上传出错");
        },
        timeout: function (xhr, editor) {
            console.log("上传超时");
        },
        customInsert: function (insertImg, result, editor) {
            // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
            // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

            // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
            var url = result.url;
            insertImg(url)

            // result 必须是一个 JSON 格式字符串！！！否则报错
        }

    };
    // 或者 var editor = new E( document.getElementById('editor') )
    editor.create();

    $('#editor').attr('style', 'height:auto;');


    layui.use(['form', 'laydate', 'table', 'upload'], function () {
        var table = layui.table;
        form = layui.form;

        var $ = layui.jquery
            , upload = layui.upload;

        tableIns = table.render({
            id: 'newsId',
            elem: '#newsList',
            url: '/news/admin/getNewsList',
            method: 'get', //默认：get请求
            title: '新闻动态列表',
            cellMinWidth: 80,
            page: true,
            request: {
                pageName: 'currPage', //页码的参数名称，默认：pageNum
                limitName: 'pageSize' //每页数据量的参数名，默认：pageSize
            },
            response: {
                statusName: 'code', //数据状态的字段名称，默认：code
                statusCode: 0, //成功的状态码，默认：0
                countName: 'total', //数据总数的字段名称，默认：count
                dataName: 'datas' //数据列表的字段名称，默认：data
            },
            /**
             * 修改table.js 中的源码得到的自定义方法。解决多层json嵌套无法渲染表格的问题
             */
            beforeRender: function (res) {
                res.total = res.page.total;
            },
            cols: [[
                // {type: 'checkbox', width: '3%', fixed: 'left'}
                 {field: 'newsTitle', title: '新闻标题', align: 'center', width: '10%'}
                , {
                    field: 'newsType', title: '新闻类型', align: 'center', width: '29%',
                    templet: function (d) {
                        if (d.newsType === 1) {
                            return '<div class="newsType">行业聚焦</div>'
                        }
                        if (d.newsType === 2) {
                            return '<div class="newsType">企业动态</div>'
                        }

                    }
                }
                , {field: 'createTime', title: '发布时间', align: 'center', width: '10%'}
                , {
                    field: 'newsImg', title: '封面图片', align: 'center', width: '25%',
                    templet: function (d) {
                        return '<div class="serviceCaseImg">' +
                            '<img src=' + d.newsImg + '></div>'
                    }
                }
                , {fixed: 'right', title: '操作', align: 'center', toolbar: '#optBar', width: '25%'}
            ]],
            done: function (res, curr, count) {
                /*使fixed列自适应单元格高度*/
                $(".layui-table-main  tr").each(function (index, val) {
                    $($(".layui-table-fixed .layui-table-body tbody tr")[index]).height($(val).height());
                    $($(".layui-table-fixed-r .layui-table-body tbody tr")[index]).height($(val).height());
                });

                // console.log(res.datas);

                pageCurr = curr;
                layer.photos({
                    photos: '.newsImg',
                    anim: 3
                })
            }
        });
        //监听提交


        //监听工具条
        table.on('tool(newsTable)', function (obj) {
            var data = obj.data;

            if (obj.event === 'del') {
                // 删除
                deleteNews(data, obj);
            } else if (obj.event === 'edit') {

                localStorage.setItem("title", data.newsTitle);
                localStorage.setItem("time", data.createTime);
                localStorage.setItem("detail", data.newsContent);

                window.location.href = "/classicCase/classicCasePreview";

            }

        });


        var form = layui.form
            , layer = layui.layer;
        var newsImg = "";

        //封面图片上传
        var uploadInst = upload.render({
            elem: '#newsImg'
            , url: '/file/imgUpload'
            , before: function (obj) {

            }
            , done: function (res) {

                //如果上传失败
                if (res.code < 0) {
                    return layer.msg('上传失败');

                } else {
                    layer.msg('图片上传成功');
                    newsImg = res.url;
                    //上传成功
                    $('#newsPhoto').attr('src', res.url); //照片回显
                }
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#newsText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
        });

        //监听提交
        form.on('submit(formNews)', function (data) {

            //获取表单值
            var newsName = data.field.newsTitle; //新闻标题
            var newsId = data.field.newsId; //新闻类型
            var newsDetail = editor.txt.html();


            console.info(newsDetail);
            debugger;
            var img = newsImg;
            var tp = $('#newsPhoto').attr('src');

            if (newsDetail.length < 15) {
                //信息框-例4
                layer.msg('新闻详情还没有输入！', {icon: 5});
                return false;
            }


            if (ValidateUtils.isEmpty(img)) {
                //信息框-例4
                layer.msg('新闻封面图片还没有选择呢！', {icon: 5});
                return false;
            }

            $.ajax({
                type: "POST",
                url: "/news/admin/addNews",
                contentType: "application/json;charset=utf-8",
                data: JSON.stringify({
                    newsTitle: newsName,
                    newsType: newsId,
                    newsContent: newsDetail,
                    newsImg: img
                }),
                datatype: 'json',
                error: function () {
                    layer.alert("发布失败");
                    layer.closeAll();
                },
                success: function (res) {

                    if (res.code == 0) {
                        layer.alert("发布成功");
                        // layer.closeAll();
                        cleanCase();
                    } else {
                        layer.alert("发布失败");
                        // layer.closeAll();
                    }
                }
            });

            return false;
        });

        //自定义验证规则
        form.verify({
            newsTitle: function (value) {
                if (value.length < 1) {
                    return '您还没输入新闻标题呢';
                }
            }
        });
    });

});


//重新加载table
function load(obj) {
    tableIns.reload({
        where: obj.field
        , page: {
            curr: pageCurr //从当前页码开始
        }
    });
}

function deleteNews(data, obj) {
    //删除
    if (null != data.newsId) {
        layer.confirm('您确定要删除吗？', {
            btn: ['确认', '取消'] //按钮
        }, function () {
            $.post("/news/admin/deleteNews", {"newsId": data.newsId}, function (data) {
                if (data.code == 0) {
                    layer.alert("删除成功", function () {
                        layer.closeAll();
                        load(obj); //刷新
                    });
                } else {
                    layer.alert("删除失败");
                }
            });
        }, function () {
            layer.closeAll();
        });
    }
}


function cleanCase() {
    //回显数据
    $("#newsTitle").val("");
    $("#newsText").val("");
    $("#newsPhoto").attr("src", "");
    editor.txt.html("");
}





